﻿using IQIGame.Onigao.Logic;
using LFloatMath.Collision2D;
using LFloatMath.Math;

namespace IQIGame.Onigao.GamePlay
{
    public class CollisionViewComponent : TComponent
    {
        public UnitView unit;
        public ColliderProxy proxy;
        public bool dirty { get; set; }
        
        protected override void OnDispose()
        {
            this.FreeProxy();
        }

        public override void OnCreate(TEntity entity)
        {
            this.unit = entity as UnitView;
        }
        
        public void InitializeCircle(LFloat fRadius)
        {
            this.FreeProxy();
            
            proxy = ColliderProxy.Fetch();
            proxy.Init(CollisionUtil.GetCirclePrefab(fRadius), unit?.pos ?? LVector2.zero);
            proxy.IsStatic = false;
            proxy.LayerType = 0;

            this.dirty = true;
            BattleManager.Instance.ctrl.collisionCtrl.AddCollider(this);
        }

        private void FreeProxy()
        {
            if (this.proxy != null)
            {
                ColliderProxy.Free(this.proxy);
                this.proxy = null;
                this.dirty = true;
                BattleManager.Instance.ctrl.collisionCtrl.RmoveCollider(this);
            }
        }

        public void SetPos(LVector2 pos)
        {
            if (this.proxy != null && this.proxy.pos != pos)
            {
                this.proxy.pos = pos;
                this.dirty = true;
            }
        }
    }
}